package controller_admin

import (
	"chitchat_http/model"
	"chitchat_http/server"
	"chitchat_http/util"
	"github.com/doujunyu/gogo/job"
	"github.com/doujunyu/gogo/sql_aid"
)
// +--------------------------------------------------------
// +管理员模块
// +--------------------------------------------------------

// AdminByLoginToUsername 管理员登录
func AdminByLoginToUsername(j *job.Job){
	if j.Input["username"] == "" {
		j.JsonSuccess(nil, "账号不能为空")
		return
	}
	if j.Input["password"] == "" {
		j.JsonSuccess(j.Input, "密码不能为空")
		return
	}
	userLoginSql, args := sql_aid.PgTable(model.TableByUserLogin).Field("id", "user_id", "is_login", "password").Where("username = ?", j.Input["username"]).ToSql()
	userLogin, err := sql_aid.DataToMap(model.PgSql.Query(userLoginSql, args...))
	if err != nil || len(userLogin) == 0 {
		j.JsonError(nil, "账户不存在")
		return
	}
	//验证密码
	if err = util.CheckHash(userLogin[0]["password"].(string), j.Input["password"]); err != nil {
		j.JsonError(nil, "密码错误")
		return
	}
	if int(userLogin[0]["is_login"].(int64)) != model.UserLoginByIsLoginNormal {
		j.JsonError(nil, "账户已被禁用")
		return
	}

	userSignSql, args := sql_aid.PgTable(model.TableByUserSign).Field("id", "user_id", "is_admin").Where("user_id = ?", userLogin[0]["user_id"].(int64)).ToSql()
	userSign, err := sql_aid.DataToMap(model.PgSql.Query(userSignSql, args...))
	if err != nil || len(userSign) == 0 {
		j.JsonError(nil, "您不是总后台人员")
		return
	}
	//验证密码
	if userSign[0]["is_admin"].(int64) == 0 {
		j.JsonError(nil, "不是管理员，无法登录！")
		return
	}

	//requestUrl := j.R.Header.Get("X-FORWARDED-FOR") //获取登录地址
	data, err := server.AdminByLogin(userLogin[0]["user_id"].(int64),util.GetCurrentIP(j.R))
	if err != nil {
		j.JsonError(nil, err.Error())
		return
	}
	j.JsonSuccess(data)


}

